package edu.dlust.trading_platform;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBase.Redis;
import edu.dlust.trading_platform.DataBase.UserSQLite;
import edu.dlust.trading_platform.ability.SendMail;
import edu.dlust.trading_platform.DataBean.random;

public class ForgetPasswordActivity extends AppCompatActivity {
    private EditText uid,code,passwd1,passwd2;
    private Button get,commit;
    private RadioGroup check;
    private ImageView backLogin;
    private boolean waits = true;
    private String mail = null;
    private String phone = null;
    private UserSQLite userSQLite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        codes();
        confirm();
        back();
    }
    private void codes(){
        check = findViewById(R.id.rdg);
        uid = findViewById(R.id.usernameEditText);
        get = findViewById(R.id.getEmailVerificationCodeButton);

        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id = uid.getText().toString();
                if (id.equals("")) {
                    Toast.makeText(ForgetPasswordActivity.this, "账号不能为空！", Toast.LENGTH_SHORT).show();
                }else{
                    String sql = "SELECT Mail,Phone From LOGINID WHERE Uid = ?";
                    new Thread(new Runnable() {
                     @Override
                        public void run() {
                            try {
                                Connection con = MySQL.getConnection();
                              PreparedStatement ps = con.prepareStatement(sql);
                                ps.setString(1, id);
                                ResultSet rs = ps.executeQuery();
                                if (rs.next()) {
                                    mail = rs.getString("Mail");
                                    phone = rs.getString("Phone");
                                    int heckedRadioButtonId = check.getCheckedRadioButtonId();
                                    if (heckedRadioButtonId == R.id.RDB_1) {
                                        random random = new random();
                                        Redis redis = new Redis();
                                        int code = random.create();
                                        SendMail sendMailTask = new SendMail(mail, code);
                                        redis.create(mail, code);
                                        sendMailTask.execute();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(ForgetPasswordActivity.this, "已成功发送验证码", Toast.LENGTH_SHORT).show();
                                            waits = false;
                                            waiting();
                                        }
                                    });
                                } else if (heckedRadioButtonId == R.id.RDB_2) {
                                        random random = new random();
                                        Redis redis = new Redis();
                                        int code = random.create();
                                        redis.create(phone, code);
                                            try {
                                                //AliyunTextMessage aliyunTextMessage = new AliyunTextMessage();
                                                //aliyunTextMessage.sendSMS(phone,Integer.toString(code));
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(ForgetPasswordActivity.this, "已成功发送验证码", Toast.LENGTH_SHORT).show();
                                                waits = false;
                                                waiting();
                                            }
                                        });
                                } else {
                                    Toast.makeText(ForgetPasswordActivity.this, "请选择您的找回方式！", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ForgetPasswordActivity.this, "账号不存在！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                            con.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                }
            }
        });
    }
    public void waiting() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                waits = true;
                timer.cancel(); // 取消定时任务
            }
        }, 60000); // 60秒等待时间，1秒 = 1000毫秒
    }
    private void confirm(){
        uid = findViewById(R.id.usernameEditText);
        code = findViewById(R.id.emailVerificationCodeEditText);
        passwd1 = findViewById(R.id.newPasswordEditText);
        passwd2 = findViewById(R.id.commitPasswordEditText);

        check = findViewById(R.id.rdg);

        commit = findViewById(R.id.confirmModifyButton);
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uuid = uid.getText().toString();
                String ccode = code.getText().toString();
                String pswd1 = passwd1.getText().toString();
                String pswd2 = passwd2.getText().toString();

                if(uuid.equals("") || ccode.equals("") || pswd1.equals("") || pswd2.equals("") || !pswd1.equals(pswd2)){
                    Toast.makeText(ForgetPasswordActivity.this, "内容不完整或两次密码不一致！", Toast.LENGTH_SHORT).show();
                }else{
                    String sql = "SELECT Mail,Uid From LOGINID WHERE Uid = ?";
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Connection con = MySQL.getConnection();
                                PreparedStatement ps = con.prepareStatement(sql);
                                ps.setString(1,uuid);
                                ResultSet rs = ps.executeQuery();
                                if (rs.next()){
                                    mail = rs.getString("Mail");
                                    phone = rs.getString("Phone");
                                    check.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                        @Override
                                        public void onCheckedChanged(RadioGroup radioGroup, int i) {
                                            if (i == R.id.RDB_1){
                                                if(CheckCode(mail,Integer.parseInt(ccode))){
                                                    updateSQL(uuid,pswd1);
                                                }else {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Toast.makeText(ForgetPasswordActivity.this, "验证码错误！", Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                }
                                            }else if(i == R.id.RDB_2){
                                                if(CheckCode(phone,Integer.parseInt(ccode))){
                                                    updateSQL(uuid,pswd1);
                                                }else {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Toast.makeText(ForgetPasswordActivity.this, "验证码错误！", Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                }
                                            }else {
                                                Toast.makeText(ForgetPasswordActivity.this, "请选择您的找回方式！", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });

                                }else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(ForgetPasswordActivity.this, "账号不存在！", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                                con.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                }
            }
        });
    }
    public boolean CheckCode(String mail, int check) {
        FutureTask<Boolean> futureTask = new FutureTask<>(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                Redis redis = new Redis();
                int result = Integer.parseInt(redis.find(mail));
                return result == check;
            }
        });

        new Thread(futureTask).start();

        try {
            return futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return false;
        }
    }
    private void updateSQL(String uid, String passwd){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String sql = "UPDATE LOGINID SET Pswd = ? WHERE Uid = ?";
                int as = 0;
                try {
                    Connection con = MySQL.getConnection();
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setString(1,passwd);
                    ps.setString(2,uid);
                    as = ps.executeUpdate();
                    if (as >=1){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ForgetPasswordActivity.this, "密码更新成功!", Toast.LENGTH_SHORT).show();
                                userSQLite.deleteUser();
                            }
                        });
                    }else {
                        Toast.makeText(ForgetPasswordActivity.this, "密码更新失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    @Override
    public boolean onKeyDown(int KeyCode, KeyEvent event){
        if (KeyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
            ForgetPasswordActivity.this.finish();
        }
        return false;
    }
    private void back(){
        backLogin = findViewById(R.id.return_login);
        backLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ForgetPasswordActivity.this.finish();
            }
        });
    }
}